import json
import urllib.parse
import urllib.request as request
import urllib.error as error
import requests

def weahter(city):
    api_url = 'http://apis.juhe.cn/simpleWeather/query'
    params_dict = {
        "city": city,  # 查询天气的城市名称，如：北京、苏州、上海
        "key": "109059211ebd676bbfdf1cd531236004",  # 您申请的接口API接口请求Key
    }
    params = urllib.parse.urlencode(params_dict)
    try:
        req = request.Request(api_url, params.encode())
        response = request.urlopen(req)
        content = response.read()
        if content:
            try:
                result = json.loads(content)
                error_code = result['error_code']
                if (error_code == 0):
                    temperature = result['result']['realtime']['temperature']
                    humidity = result['result']['realtime']['humidity']
                    info = result['result']['realtime']['info']
                    wid = result['result']['realtime']['wid']
                    direct = result['result']['realtime']['direct']
                    power = result['result']['realtime']['power']
                    aqi = result['result']['realtime']['aqi']
                    print("温度：%s\n湿度：%s\n天气：%s\n天气标识：%s\n风向：%s\n风力：%s\n空气质量：%s" % (
                        temperature, humidity, info, wid, direct, power, aqi))
                    return temperature, humidity, info, power, aqi
                    # temp = int(temperature)
                    # my_say = " "
                    # if (temp <= -9):
                    #     my_say = "\n 天气预报从来没有出现过这么低的温度，那么我喜欢你～"
                    # if (temp <= 10):
                    #     my_say = "\n 今天要冻死了！！多穿衣服"
                    # if (10 < temp < 20):
                    #     my_say = "\n 我感觉今天挺凉爽的，你可以穿的舒服一点儿～我想看你美美的照片～"
                    # if (20 <= temp < 30):
                    #     my_say = "\n 这天气太适合穿小裙子了！我要看，我要看！"
                    # if (temp >= 30):
                    #     my_say = "\n 讲真的，这么热，好好擦防晒，戴帽子！"
                    # twitter = "郑州今天 " + temperature + "度" + "，天气是" + info + my_say + "\n 顺便问一句，你～有想我吗？"
                    # title1 = temperature + "度" + info + "天"
                    # push(SCKEY, twitter, title1)

                else:
                    print("请求失败:%s %s" % (result['error_code'], result['reason']))
            except Exception as e:
                print("解析结果异常：%s" % e)
        else:
            # 可能网络异常等问题，无法获取返回内容，请求异常
            print("请求异常")
    except error.HTTPError as err:
        print(err)
    except error.URLError as err:
        # 其他异常
        print(err)
